import { app } from "common/jscloud";
import {cell, CellGroup, CellBlock, createStore, register, store} from 'components/form'
import _message from "components/items/message";

const lib = ao2.lib
const nav = Pager.nav
const message = _message()  // 弹窗实例
const currentCloudCollection = () => {
  return ao2.CLOUD_COLLECTION
}


//弹窗编辑
export function popupRowEditor(params, columns) {
  const formConfig = []
  columns.forEach(fild => {
    for (const [key, value] of Object.entries(fild)) {
      const title = value.title
      const input = value.input
      if (input) {
        if (typeof input === 'function') {
          input = input()
        }
        const $input = Object.assign({}, input)
        if (!$input.id) $input.id = key+'-'+lib.uuid(6)
        $input.value = params[key]
        formConfig.push({
          title, 
          input: $input
        })
      }
    }
  })
  return <CellGroup data={formConfig} store={store} />
}

async function getTempFileURL(val){
  return new Promise((resolve, reject)=>{
    let temp = val.split(',')
    let cloudsrc = []
    let attr = []
    let target = []
    temp.forEach(img=>{
      let {url, query, hash, hasQuery} = lib.urlTOquery(img)  
      cloudsrc.push(url)
      attr.push(query)
    })
    app.getTempFileURL({ fileList: cloudsrc }).then(result=>{
      const fileList = result.fileList
      fileList.forEach((fileItem, ii)=>{
        if (fileItem.code === 'SUCCESS') {
          let $url = fileItem.download_url+'#'+fileItem.fileID
          let $query = attr[ii]
          target.push(lib.queryTOurl($url, $query))
        }
      })
      resolve(target.join(','))
    })
  })
}

// async function getTempFileURLX(val){
//   console.log('======= bbbb');
//   return new Promise((resolve, reject) =>{
//     let   temp = val.split(',')
//     let   P = temp.map(img=>{
//       return new Promise((rso, rej) =>{
//         let {url, query, hash, hasQuery} = lib.urlTOquery(img)  
//         app.getTempFileURL({ fileList: [url] }).then(result=>{
//           let fileList = result.fileList
//           if (fileList.length && fileList[0].code === "SUCCESS" ) {
//             let $url = fileList[0].download_url+'#'+fileList[0].fileID
//             url = lib.queryTOurl($url, query)
//             rso(url)
//           }
//         })
//       })
//     })

//     Promise.all(P, function(res){
//       res = res.filter(item=>!!item)
//       resolve(res.join(','))
//     })
//   })
// }


// 列表页
// bootstrapTable 响应事件方法合集
export const actionEvents = function(
  actionName='default', 
  getTableInstance, 
  columnsName, 
  columns, 
  collectionName
){

  if (typeof actionName === 'function') {
    getTableInstance = actionName
    actionName = 'default'
  }





  // 默认事件
  const defaultAction =  {
    'click .edit': async function (e, value, row, index) {
      const id = row.id
      row.collectionName = collectionName  // 指定使用的字段
      row.columnsName = columnsName  // 指定使用的字段
      row.columnsFilds = columns   // 此时是字符串?

      let tmp = {}
      for (const [key, value] of Object.entries(row)) {
        if (typeof value === 'string' && value.indexOf('cloud://') === 0) {
          tmp[key] = value
        }
      }

      // 获取腾讯云的媒体数据
      for (const [key, value] of Object.entries(tmp)) {
        row[key] = await getTempFileURL(value)
      }
      
      // for (const [key, value] of Object.entries(tmp)) {
      //   let result = await app.getTempFileURL({ fileList: [value] })
      //   let fileList = result.fileList
      //   if (fileList.length && fileList[0].code === "SUCCESS" ) {
      //     row[key] = fileList[0].download_url+'#'+fileList[0].fileID
      //   }
      // }

      row.__media = tmp





      nav.redirectTo({
        url: '/order/detail',
        data: row,
        beforeNav(to, from, next) {
          next()
        }
      })
    },
    // 弹出层编辑
    'click .popedit': function (e, value, row, index) {
      const tableInstance = getTableInstance()
      message.modal({
        type: 'options',
        title: '编辑',
        body: [
          popupRowEditor(row, columns)
        ],
        showFooter: true,
        showConfirm: true,
        showCancel: true,
        cbConfirm: function(params) {
          message.close('modal')
          let newRow = { id: row.id }
          const storeValues = store.storeHelper.value()  // 取得所有表单值
          for (const [key, value] of Object.entries(storeValues)) {
            const ky = key.substring(0, key.indexOf('-'))
            newRow[ky] = value
          }

          tableInstance.btTable.bootstrapTable('updateRow', {
            index: index,
            row: newRow
          })

          currentCloudCollection().doc.set(row.id, newRow)
        }
      })
    },
    'click .remove': function (e, value, row, index) {
      const ids = row.id        //需要字符串
      const tableInstance = getTableInstance()
      message.modal({
        type: 'normal',
        title: '是否删除此数据？',
        showFooter: true,
        showConfirm: true,
        showCancel: true,
        cbConfirm: function(params) {
          message.close('modal')
          tableInstance.btTable.bootstrapTable('remove', {
            field: 'id',
            values: ids
          })
          setTimeout(() => {
            currentCloudCollection().doc.delete(row.id)
          }, 100);
        },
        bgClose: true
      })
    }
  };





  const managerAction = {
    'click .remove': function (e, value, row, index) {
      const ids = row.id        //需要字符串
      const tableInstance = getTableInstance()
      message.modal({
        type: 'normal',
        title: '是否删除此数据？',
        showFooter: true,
        showConfirm: true,
        showCancel: true,
        cbConfirm: function(params) {
          message.close('modal')
          tableInstance.btTable.bootstrapTable('remove', {
            field: 'id',
            values: ids
          })
          setTimeout(() => {
            currentCloudCollection().doc.delete(row.id)
            Fetcher.post('/api/databaseCollectionDelete', {
              collection_name: collectionName
            })
          }, 100);
        },
        bgClose: true
      })
    }
  }






  // 通过actionName返回指定事件
  const allActions = {
    default: defaultAction,
    'CLOUD-TABLE-MANAGER': Object.assign({}, defaultAction, managerAction)
  }
  



  return actionName ? allActions[actionName] ? allActions[actionName] : defaultAction : defaultAction
}